<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>虚拟支付 - 有偿知识问答系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }
        .payment-container {
            max-width: 500px;
            margin: 50px auto;
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        .payment-info {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 6px;
            margin-bottom: 25px;
        }
        .payment-info p {
            margin: 10px 0;
            color: #666;
        }
        .payment-info .amount {
            font-size: 24px;
            font-weight: bold;
            color: #e74c3c;
        }
        .payment-methods {
            margin-bottom: 30px;
        }
        .payment-method {
            display: flex;
            align-items: center;
            padding: 15px;
            border: 2px solid #eaeaea;
            border-radius: 6px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .payment-method:hover {
            border-color: #007bff;
            background-color: #f0f7ff;
        }
        .payment-method.selected {
            border-color: #007bff;
            background-color: #e3f2fd;
        }
        .payment-method input[type="radio"] {
            margin-right: 15px;
            width: 18px;
            height: 18px;
        }
        .payment-method .method-name {
            font-weight: 500;
            color: #333;
        }
        .payment-actions {
            display: flex;
            justify-content: space-between;
        }
        .btn {
            padding: 12px 30px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .btn-cancel {
            background-color: #6c757d;
            color: white;
        }
        .btn-cancel:hover {
            background-color: #5a6268;
        }
        .btn-pay {
            background-color: #28a745;
            color: white;
        }
        .btn-pay:hover {
            background-color: #218838;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            display: none;
        }
        .loading-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            text-align: center;
        }
        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="payment-container">
        <h2>金币充值 - 虚拟支付</h2>
        
        <div class="payment-info">
            <p>充值账户: <span id="paymentUsername">--</span></p>
            <p>充值金币: <span id="paymentAmount" class="amount">0</span> 金币</p>
            <p>当前余额: <span id="currentBalance">0</span> 金币</p>
        </div>
        
        <div class="payment-methods">
            <div class="payment-method" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="alipay" checked>
                <span class="method-name">支付宝</span>
            </div>
            <div class="payment-method" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="wechat">
                <span class="method-name">微信支付</span>
            </div>
            <div class="payment-method" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="card">
                <span class="method-name">银行卡</span>
            </div>
        </div>
        
        <div class="payment-actions">
            <button class="btn btn-cancel" onclick="cancelPayment()">取消</button>
            <button class="btn btn-pay" onclick="confirmPayment()">确认支付</button>
        </div>
    </div>
    
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-content">
            <div class="loading-spinner"></div>
            <p>正在处理支付请求，请稍候...</p>
        </div>
    </div>

    <script>
        // 从URL获取参数
        function getUrlParams() {
            const params = {};
            const queryString = window.location.search.substring(1);
            const pairs = queryString.split('&');
            for (const pair of pairs) {
                const [key, value] = pair.split('=');
                params[key] = decodeURIComponent(value || '');
            }
            return params;
        }
        
        // 安全地从localStorage获取用户ID
        function getUserIdFromStorage() {
            try {
                const savedUserId = localStorage.getItem('userId');
                if (savedUserId && !isNaN(savedUserId)) {
                    return parseInt(savedUserId);
                }
            } catch (error) {
                console.error('获取用户ID失败:', error);
            }
            return null;
        }
        
        // 选择支付方式
        function selectPaymentMethod(element) {
            // 移除所有选中状态
            document.querySelectorAll('.payment-method').forEach(el => {
                el.classList.remove('selected');
            });
            // 添加当前选中状态
            element.classList.add('selected');
            // 选中对应的radio按钮
            element.querySelector('input[type="radio"]').checked = true;
        }
        
        // 初始化页面
        function initPaymentPage() {
            const params = getUrlParams();
            const amount = params.amount || 0;
            const userId = params.userId || '';
            
            // 设置充值金额
            document.getElementById('paymentAmount').textContent = amount;
            
            // 获取用户信息（仅显示，不影响充值逻辑）
            if (userId) {
                try {
                    const userIdNum = parseInt(userId);
                    if (!isNaN(userIdNum)) {
                        fetch(`/knowledge-qa/api/user/info/${userIdNum}`)
                            .then(response => response.json())
                            .then(data => {
                                if (data.success && data.user) {
                                    document.getElementById('paymentUsername').textContent = data.user.username || '未知用户';
                                    document.getElementById('currentBalance').textContent = data.user.coinBalance || 0;
                                }
                            })
                            .catch(error => {
                                console.error('获取用户信息失败:', error);
                            });
                    }
                } catch (error) {
                    console.error('用户ID格式错误:', error);
                }
            }
        }
        
        // 取消支付
        function cancelPayment() {
            if (window.opener && !window.opener.closed) {
                window.close();
            } else {
                window.history.back();
            }
        }
        
        // 确认支付 - 简化版
        function confirmPayment() {
            const params = getUrlParams();
            // 从URL参数获取用户ID和充值金额
            let userId = params.userId;
            const amount = params.amount;
            
            console.log('获取到的用户ID(URL参数):', userId);
            
            // 检查用户ID是否为字符串"undefined"或无效
            if (!userId || userId === 'undefined' || userId === 'null') {
                console.log('URL参数中未检测到有效用户ID，尝试从localStorage获取');
                // 从localStorage获取用户ID作为备选方案
                userId = getUserIdFromStorage();
                
                // 如果localStorage中也没有有效用户ID，则提示错误
                if (!userId || isNaN(userId) || userId <= 0) {
                    alert('未检测到有效用户ID，请重新登录后再发起充值');
                    console.error('无法获取有效用户ID');
                    return;
                }
            }
            
            // 转换用户ID为数字类型并进行严格验证
            const userIdNum = Number(userId);
            if (isNaN(userIdNum) || !Number.isInteger(userIdNum) || userIdNum <= 0) {
                alert('用户ID格式错误，请使用有效的数字ID');
                console.error('用户ID验证失败:', userId);
                return;
            }
            
            console.log('最终使用的用户ID:', userIdNum);
            
            // 验证和转换充值金额
            const rechargeAmount = parseInt(amount);
            if (isNaN(rechargeAmount) || rechargeAmount <= 0) {
                alert('充值金额无效');
                return;
            }
            
            // 显示加载动画
            document.getElementById('loadingOverlay').style.display = 'flex';
            
            // 直接发送充值请求到后端
            fetch('/knowledge-qa/api/coin/recharge', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({userId: userIdNum, amount: rechargeAmount})
            })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载动画
                document.getElementById('loadingOverlay').style.display = 'none';
                
                if (data.success) {
                    // 支付成功，显示成功消息并跳转
                    alert('充值成功！金币已添加到您的账户');
                    if (window.opener && !window.opener.closed) {
                        window.opener.location.reload();
                        window.close();
                    } else {
                        window.location.href = '/knowledge-qa/static/pages/user_info.html';
                    }
                } else {
                    // 支付失败，显示失败消息
                    alert(data.message || '充值失败，请稍后重试');
                }
            })
            .catch(error => {
                // 隐藏加载动画
                document.getElementById('loadingOverlay').style.display = 'none';
                
                console.error('充值请求失败:', error);
                alert('充值网络异常，请检查网络连接后重试');
            });
        }
        
        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', initPaymentPage);
    </script>
</body>
</html>